<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="预约人姓名" prop="applicantName" label-width="85px">
        <el-input
          v-model="queryParams.applicantName"
          placeholder="请输入预约人姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入手机号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="预约状态" prop="status" style="width: 250px;">
        <el-select 
          v-model="queryParams.status" 
          placeholder="请选择" 
          clearable
          @change="handleQuery"
        >
          <el-option label="待上门" value="待上门"></el-option>
          <el-option label="已完成" value="已完成"></el-option>
          <el-option label="已取消" value="已取消"></el-option>
          <el-option label="已过期" value="已过期"></el-option>
        </el-select>
      </el-form-item>
      <br>
      <el-form-item label="预约时间" prop="appointmentTime">
        <el-date-picker clearable
          v-model="queryParams.appointmentTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择预约时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
      
    </el-form>

    <!-- 预约类型筛选按钮 -->
    <div class="status-buttons">
      <div 
        class="status-btn" 
        :class="{ active: selectedType === '' }"
        @click="handleClick('')"
      >
        全部
      </div>
      <!-- 预约类型：参观预约、探访预约 -->
      <div 
        class="status-btn"
        :class="{ active: selectedType === '参观预约' }"
        @click="handleClick('参观预约')"
      >
        参观预约
      </div>
      <div 
        class="status-btn"
        :class="{ active: selectedType === '探访预约' }"
        @click="handleClick('探访预约')"
      >
        探访预约
      </div>
    </div>

    <!-- 表格：按预约状态控制到院按钮 -->
    <el-table v-loading="loading" :data="yuyueList" @selection-change="handleSelectionChange">
      <el-table-column label="序号" align="center"><template #default="scope">
        {{ scope.$index + 1 }}
      </template></el-table-column>
      <el-table-column label="预约类型" align="center" prop="appointmentType" />
      <el-table-column label="预约人姓名" align="center" prop="applicantName" />
      <el-table-column label="手机号" align="center" prop="phone" width="150"/>
      <el-table-column label="老人姓名" align="center" width="150">
        <template #default="scope">
          {{ scope.row.elderlyName || "-" }}
        </template>
      </el-table-column>
      <el-table-column label="预约时间" align="center" prop="appointmentTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.appointmentTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" width="150">
        <template #default="scope">
          {{ scope.row.creatorName || "-" }}
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="预约状态" align="center" prop="status">
        <template #default="scope">
          <!-- 按状态文本显示不同颜色标签 -->
          <el-tag :type="getStatusTagType(scope.row.status)">
            {{ scope.row.status || "未设置" }}
          </el-tag>
        </template>
      </el-table-column>
      <!-- 操作列：到院按钮（按状态控制可用性） -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <!-- 到院按钮：仅“待上门”“已过期”可点击 -->
          <el-button 
            link 
            type="primary" 
            @click="handleArrival(scope.row)"
            :disabled="!isArrivalBtnEnable(scope.row.status)"
            style="margin-right: 8px"
          >
            到院
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 原有：添加或修改预约登记对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="yuyueRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="微信登录账号外键" prop="wxUserId">
          <el-input v-model="form.wxUserId" placeholder="请输入微信登录账号外键" />
        </el-form-item>
        <el-form-item label="预约人姓名" prop="applicantName">
          <el-input v-model="form.applicantName" placeholder="请输入预约人姓名" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="老人外键编号" prop="elderlyId">
          <el-input v-model="form.elderlyId" placeholder="请输入老人外键编号" />
        </el-form-item>
        <el-form-item label="预约时间" prop="appointmentTime">
          <el-date-picker clearable
            v-model="form.appointmentTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择预约时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="创建人" prop="creator">
          <el-input v-model="form.creator" placeholder="请输入创建人" />
        </el-form-item>
        <el-form-item label="到院时间" prop="arrivalTime">
          <el-date-picker clearable
            v-model="form.arrivalTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择到院时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="预约状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择预约状态" required>
            <el-option label="待上门" value="待上门"></el-option>
            <el-option label="已完成" value="已完成"></el-option>
            <el-option label="已取消" value="已取消"></el-option>
            <el-option label="已过期" value="已过期"></el-option>
          </el-select>
        </el-form-item>
        <!-- 新增预约类型选择 -->
        <el-form-item label="预约类型" prop="appointmentType">
          <el-select v-model="form.appointmentType" placeholder="请选择预约类型" required>
            <el-option label="参观预约" value="参观预约"></el-option>
            <el-option label="探访预约" value="探访预约"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="逻辑删除" prop="isDeleted">
          <el-input v-model="form.isDeleted" placeholder="请输入逻辑删除" />
        </el-form-item>
        <el-form-item label="额外字段1" prop="extraField1">
          <el-input v-model="form.extraField1" placeholder="请输入额外字段1" />
        </el-form-item>
        <el-form-item label="额外字段2" prop="extraField2">
          <el-input v-model="form.extraField2" placeholder="请输入额外字段2" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 新增：确认到院时间弹窗 -->
    <el-dialog 
      title="确认到院时间" 
      v-model="arrivalDialogVisible" 
      width="400px"
      append-to-body
    >
      <el-form ref="arrivalFormRef" :model="arrivalForm" :rules="arrivalRules" label-width="100px">
        <el-form-item label="来访时间" prop="arrivalTime">
          <el-date-picker
            v-model="arrivalForm.arrivalTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择来访时间"
            clearable
            required
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="arrivalDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleConfirmArrival" :loading="arrivalLoading">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Yuyue">
import { listYuyue, getYuyue, delYuyue, addYuyue, updateYuyue } from "@/api/commanage/yuyue"
const { proxy } = getCurrentInstance()

// 原有：基础变量
const yuyueList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const selectedType = ref('') // 预约类型筛选（文本匹配）

// 新增：到院弹窗相关变量
const arrivalDialogVisible = ref(false) // 弹窗显示状态
const arrivalLoading = ref(false) // 弹窗提交加载状态
const currentArrivalRow = ref(null) // 当前点击到院的行数据
// 到院表单数据
const arrivalForm = reactive({
  arrivalTime: '' // 来访时间（日期+时间）
})
// 到院表单验证规则
const arrivalRules = reactive({
  arrivalTime: [
    { required: true, message: "请选择来访时间", trigger: "change" }
  ]
})
// 到院表单引用
const arrivalFormRef = ref()

// 原有：表单数据（优化规则+新增类型字段）
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    applicantName: null,
    phone: null,
    appointmentTime: null,
    status: null, 
    appointmentType: null, // 新增：预约类型筛选参数
  },
  rules: {
    applicantName: [
      { required: true, message: "请输入预约人姓名", trigger: "blur" }
    ],
    phone: [
      { required: true, message: "请输入手机号", trigger: "blur" },
      { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号", trigger: "blur" }
    ],
    appointmentTime: [
      { required: true, message: "请选择预约时间", trigger: "change" }
    ],
    status: [
      { required: true, message: "请选择预约状态", trigger: "change" }
    ],
    // 新增：预约类型验证规则
    appointmentType: [
      { required: true, message: "请选择预约类型", trigger: "change" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 原有：查询预约登记列表（支持类型文本筛选） */
function getList() {
  loading.value = true
  listYuyue(queryParams.value).then(response => {
    yuyueList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

/** 新增：判断到院按钮是否可用（按状态文本） */
function isArrivalBtnEnable(status) {
  // 规则：仅“待上门”“已过期”可点击，其他状态置灰
  const enableStatus = ["待上门", "已过期"]
  return enableStatus.includes(status)
}

/** 新增：按状态文本设置标签颜色（提升视觉区分） */
function getStatusTagType(status) {
  switch (status) {
    case "待上门": return "info" // 蓝色
    case "已完成": return "success" // 绿色
    case "已取消": return "danger" // 红色
    case "已过期": return "warning" // 黄色
    default: return "default" // 灰色
  }
}

/** 新增：点击到院按钮，打开弹窗 */
function handleArrival(row) {
  currentArrivalRow.value = row // 保存当前行数据
  arrivalForm.arrivalTime = '' // 重置表单
  arrivalDialogVisible.value = true // 打开弹窗
}

/** 新增：确认到院时间，更新状态为“已完成” */
async function handleConfirmArrival() {
  try {
    // 表单验证
    await proxy.$refs.arrivalFormRef.validate()
    arrivalLoading.value = true

    // 构建更新参数（传递到院时间+目标状态）
    const updateData = {
      id: currentArrivalRow.value.id, // 预约记录ID
      status: "已完成", // 目标状态：已完成
      arrivalTime: arrivalForm.arrivalTime // 选中的到院时间
    }

    // 调用接口更新状态
    await updateYuyue(updateData)

    // 操作成功反馈
    proxy.$modal.msgSuccess("确认到院成功，预约状态已更新为【已完成】")
    arrivalDialogVisible.value = false
    getList() // 重新加载列表，显示最新状态
  } catch (error) {
    console.error("确认到院失败：", error)
    proxy.$modal.msgError("确认到院失败，请重试")
  } finally {
    arrivalLoading.value = false
  }
}

/** 修改：类型筛选按钮点击事件（文本匹配） */
const handleClick = (value) => {
  selectedType.value = value
  queryParams.value.appointmentType = value || null // 空值查询全部
  queryParams.value.pageNum = 1 // 重置页码
  getList()
}

// 原有：取消按钮
function cancel() {
  open.value = false
  reset()
}

// 原有：表单重置（新增类型字段重置）
function reset() {
  form.value = {
    id: null,
    appointmentType: null, // 预约类型
    wxUserId: null,
    applicantName: null,
    phone: null,
    elderlyId: null,
    appointmentTime: null,
    creator: null,
    createTime: null,
    status: null,
    arrivalTime: null,
    isDeleted: null,
    extraField1: null,
    extraField2: null
  }
  proxy.resetForm("yuyueRef")
}

// 原有：搜索按钮操作
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

// 原有：重置按钮操作（重置类型筛选）
function resetQuery() {
  selectedType.value = ''
  queryParams.value.appointmentType = null
  proxy.resetForm("queryRef")
  handleQuery()
}

// 原有：多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

// 原有：新增按钮操作
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加预约登记"
}

// 原有：修改按钮操作
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getYuyue(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改预约登记"
  })
}

// 原有：提交按钮
function submitForm() {
  proxy.$refs["yuyueRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateYuyue(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addYuyue(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

// 原有：删除按钮操作
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除预约登记编号为"' + _ids + '"的数据项？').then(function() {
    return delYuyue(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

// 原有：导出按钮操作
function handleExport() {
  proxy.download('commanage/yuyue/export', {
    ...queryParams.value
  }, `yuyue_${new Date().getTime()}.xlsx`)
}

// 时间格式化函数
function parseTime(time, format = '{y}-{m}-{d} {h}:{i}:{s}') {
  if (!time) return ''
  const date = new Date(time)
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds()
  }
  return format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    return value.toString().padStart(2, "0")
  })
}

// 初始化加载列表
getList()
</script>

<style scoped>
/* 原有样式保持不变 */
.status-buttons {
  display: flex;
  gap: 12px;
  padding: 8px 16px;
  background-color: #F2F2F2;
  margin: 10px 0;
  width: fit-content;
  border-radius: 4px;
  flex-wrap: wrap;
}

.status-btn {
  padding: 6px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  color: #303133;
  transition: all 0.2s;
}

.status-btn.active {
  background: #fff;
  color: #1890ff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
}

.status-btn:not(.active):hover {
  background: #e5e7eb;
}

.el-dialog .el-form {
  margin-top: 16px;
}

.el-dialog .dialog-footer {
  margin-top: 24px;
}

.el-table .el-tag {
  padding: 4px 8px;
  font-size: 12px;
}

.small-padding .el-button {
  padding: 0 6px;
}
</style>